<template>
  <div class="lov-cascade-demo">
    <div class="page-header">
      <h2>LOV 级联选择演示</h2>
      <p>演示如何实现先选择班级，再根据班级筛选学生</p>
    </div>

    <el-card class="demo-card">
      <template #header>
        <div class="card-header">
          <span>级联选择示例：班级 → 学生</span>
        </div>
      </template>

      <el-form :model="form" label-width="120px">
        <el-form-item label="选择班级">
          <lov-select
            ref="classLovRef"
            v-model="form.classId"
            v-model:display-text="form.className"
            code="LOV_CLASS"
            placeholder="请先选择班级"
            @change="handleClassChange"
            style="width: 400px"
          />
        </el-form-item>

        <el-form-item label="班级ID">
          <el-input v-model="form.classId" readonly style="width: 400px" />
        </el-form-item>

        <el-form-item label="班级名称">
          <el-input v-model="form.className" readonly style="width: 400px" />
        </el-form-item>

        <el-divider />

        <el-form-item label="选择学生">
          <lov-select
            ref="studentLovRef"
            v-model="form.studentId"
            v-model:display-text="form.studentName"
            code="LOV_STUDENT_BY_CLASS"
            placeholder="请先选择班级，然后选择学生"
            @change="handleStudentChange"
            :on-query="handleStudentQuery"
            style="width: 400px"
            :disabled="!form.classId"
          />
          <el-text v-if="!form.classId" type="info" size="small" style="margin-left: 10px">
            请先选择班级
          </el-text>
        </el-form-item>

        <el-form-item label="学号">
          <el-input v-model="form.studentId" readonly style="width: 400px" />
        </el-form-item>

        <el-form-item label="学生姓名">
          <el-input v-model="form.studentName" readonly style="width: 400px" />
        </el-form-item>

        <el-form-item label="年龄">
          <el-input v-model="form.studentAge" readonly style="width: 400px" />
        </el-form-item>
      </el-form>

      <div class="info-section">
        <h3>选中的数据：</h3>
        <div class="data-display">
          <div class="data-item">
            <strong>班级信息：</strong>
            <pre>{{ selectedClass || '暂无选择' }}</pre>
          </div>
          <div class="data-item">
            <strong>学生信息：</strong>
            <pre>{{ selectedStudent || '暂无选择' }}</pre>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="demo-card">
      <template #header>
        <div class="card-header">
          <span>实现说明</span>
        </div>
      </template>

      <div class="instructions">
        <h3>实现原理：</h3>
        <ol>
          <li>用户首先选择班级，触发 <code>@change</code> 事件</li>
          <li>在 <code>handleClassChange</code> 中保存班级信息</li>
          <li>学生选择框设置为禁用状态，直到选择班级后才启用</li>
          <li>给学生LOV组件配置 <code>:query</code> 回调函数</li>
          <li>当用户点击学生LOV时，自动执行query回调，动态设置查询参数</li>
          <li>后端使用MyBatis动态SQL根据班级ID筛选学生</li>
        </ol>

        <h3>关键代码（类似KendoUI的query方式）：</h3>
        <div class="code-block">
          <pre><code>// 1. 班级选择变化事件
function handleClassChange(row) {
  if (row) {
    form.classId = row.class_id
    // 清空学生选择
    form.studentId = ''
  }
}

// 2. 给学生LOV配置onQuery回调
&lt;lov-select
  v-model="form.studentId"
  code="LOV_STUDENT_BY_CLASS"
  :on-query="handleStudentQuery"
  :disabled="!form.classId"
/&gt;

// 3. 在onQuery回调中动态设置查询参数
function handleStudentQuery(e) {
  // 根据班级下拉框取得选中的值
  if (form.classId) {
    // 设置查询SQL中的classId参数
    e.param['classId'] = form.classId
  } else {
    ElMessage.warning('请先选择班级')
  }
}</code></pre>
        </div>

        <h3>后端SQL配置示例（LOV_STUDENT_BY_CLASS）：</h3>
        <div class="code-block">
          <pre><code>SELECT
  stu_id,
  stu_name,
  stu_age,
  class_id
FROM student
&lt;where&gt;
  &lt;if test="classId != null and classId != ''"&gt;
    AND class_id = #{classId}
  &lt;/if&gt;
  &lt;if test="stu_name != null and stu_name != ''"&gt;
    AND stu_name LIKE CONCAT('%', #{stu_name}, '%')
  &lt;/if&gt;
&lt;/where&gt;
ORDER BY stu_id</code></pre>
        </div>

        <h3>使用场景：</h3>
        <ul>
          <li>✅ 部门 → 员工</li>
          <li>✅ 省份 → 城市 → 区县</li>
          <li>✅ 类别 → 商品</li>
          <li>✅ 客户 → 联系人</li>
          <li>✅ 任何需要上下级关联的场景</li>
        </ul>
      </div>
    </el-card>

    <el-card class="demo-card">
      <template #header>
        <div class="card-header">
          <span>高级示例：三级级联（班级 → 年级筛选学生 → 科目筛选成绩）</span>
        </div>
      </template>

      <el-form :model="advancedForm" label-width="120px">
        <el-form-item label="选择班级">
          <lov-select
            ref="advClassLovRef"
            v-model="advancedForm.classId"
            code="LOV_CLASS"
            placeholder="请选择班级"
            @change="handleAdvClassChange"
            style="width: 400px"
          />
        </el-form-item>

        <el-form-item label="年级筛选">
          <el-radio-group
            v-model="advancedForm.gradeFilter"
            :disabled="!advancedForm.classId"
            @change="handleGradeFilterChange"
          >
            <el-radio value="">全部</el-radio>
            <el-radio value="1">一年级</el-radio>
            <el-radio value="2">二年级</el-radio>
            <el-radio value="3">三年级</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="选择学生">
          <lov-select
            ref="advStudentLovRef"
            v-model="advancedForm.studentId"
            code="LOV_STUDENT_BY_CLASS"
            placeholder="请选择学生"
            @change="handleAdvStudentChange"
            :on-query="handleAdvStudentQuery"
            style="width: 400px"
            :disabled="!advancedForm.classId"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleAdvancedQuery"
            :disabled="!advancedForm.classId"
          >
            应用高级筛选
          </el-button>
          <el-button @click="handleResetAdvanced">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="info-section" v-if="advancedResult">
        <h3>高级筛选结果：</h3>
        <pre>{{ advancedResult }}</pre>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import LovSelect from '@/components/lov/LovSelect.vue'

const form = reactive({
  classId: '',
  className: '',
  studentId: '',
  studentName: '',
  studentAge: ''
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const selectedClass = ref<any>(null)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const selectedStudent = ref<any>(null)

const classLovRef = ref()
const studentLovRef = ref()

// 班级选择变化
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleClassChange(row: any) {
  console.log('选中的班级：', row)
  selectedClass.value = row

  if (row) {
    // v-model 已自动更新 form.classId
    // v-model:display-text 已自动更新 form.className
    // 只需要清空学生选择
    form.studentId = ''
    form.studentName = ''
    form.studentAge = ''
    selectedStudent.value = null
  } else {
    // v-model 和 v-model:display-text 会自动清空
    // 只需要清空学生选择
    form.studentId = ''
    form.studentName = ''
    form.studentAge = ''
    selectedStudent.value = null
  }
}

// 学生LOV的query回调函数
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleStudentQuery(e: any) {
  // 动态设置查询参数，根据选中的班级ID筛选学生
  if (form.classId) {
    e.param['classId'] = form.classId
  } else {
    ElMessage.warning('请先选择班级')
  }
}

// 学生选择变化
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleStudentChange(row: any) {
  console.log('选中的学生：', row)
  selectedStudent.value = row

  if (row) {
    // v-model 已自动更新 form.studentId
    // v-model:display-text 已自动更新 form.studentName
    // 只需要设置年龄字段
    form.studentAge = row.stu_age || row.studentAge || ''
  } else {
    // v-model 和 v-model:display-text 会自动清空
    // 只需要清空年龄
    form.studentAge = ''
  }
}

// 监听班级变化，清空学生选择
watch(() => form.classId, (newClassId, oldClassId) => {
  // 当班级变化时，清空学生选择
  if (newClassId !== oldClassId) {
    form.studentId = ''
    form.studentName = ''
    form.studentAge = ''
    selectedStudent.value = null
  }
})

// ==================== 高级示例 ====================
const advancedForm = reactive({
  classId: '',
  gradeFilter: '',
  studentId: ''
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const advancedResult = ref<any>(null)

const advClassLovRef = ref()
const advStudentLovRef = ref()

// 高级示例：班级选择变化
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleAdvClassChange(row: any) {
  console.log('高级示例 - 选中的班级：', row)
  if (row) {
    // 注意：advancedForm.classId 已经通过 v-model 自动更新了，无需手动设置
    // 清空学生选择
    advancedForm.studentId = ''
  } else {
    // 清空时也不需要设置 advancedForm.classId，因为 v-model 会处理
    advancedForm.gradeFilter = ''
    advancedForm.studentId = ''
  }
}

// 高级示例：年级筛选变化
function handleGradeFilterChange() {
  // 清空学生选择
  advancedForm.studentId = ''
}

// 高级示例：学生LOV的query回调函数
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleAdvStudentQuery(e: any) {
  // 动态设置查询参数
  if (advancedForm.classId) {
    e.param['classId'] = advancedForm.classId

    // 如果有年级筛选，也加入参数
    if (advancedForm.gradeFilter) {
      e.param['grade'] = advancedForm.gradeFilter
    }
  } else {
    ElMessage.warning('请先选择班级')
  }
}

// 高级示例：学生选择变化
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleAdvStudentChange(row: any) {
  console.log('高级示例 - 选中的学生：', row)
}

// 高级示例：应用高级筛选
async function handleAdvancedQuery() {
  if (!advancedForm.classId) {
    ElMessage.warning('请先选择班级')
    return
  }

  if (!advStudentLovRef.value) {
    ElMessage.error('组件引用未初始化')
    return
  }

  try {
    // 构建查询参数
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const params: Record<string, any> = {
      classId: advancedForm.classId
    }

    if (advancedForm.gradeFilter) {
      params.grade = advancedForm.gradeFilter
    }

    console.log('高级筛选参数：', params)

    // 打开LOV对话框并应用筛选
    await advStudentLovRef.value.openDialogWithCustomQuery(params)

    advancedResult.value = {
      classId: advancedForm.classId,
      gradeFilter: advancedForm.gradeFilter || '全部',
      queryTime: new Date().toLocaleString()
    }

    ElMessage.success('已应用筛选条件')
  } catch (error) {
    console.error('高级查询失败：', error)
  }
}

// 重置高级示例
function handleResetAdvanced() {
  advancedForm.classId = ''
  advancedForm.gradeFilter = ''
  advancedForm.studentId = ''
  advancedResult.value = null
}
</script>

<style scoped>
.lov-cascade-demo {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
}

.page-header p {
  margin: 0;
  color: #666;
}

.demo-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}

.info-section {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.info-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #409eff;
}

.data-display {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.data-item {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.data-item strong {
  display: block;
  margin-bottom: 10px;
  color: #303133;
}

.data-item pre {
  margin: 0;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 13px;
}

.instructions h3 {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #409eff;
}

.instructions ul {
  margin: 10px 0;
  padding-left: 20px;
}

.instructions ul li {
  margin: 8px 0;
  line-height: 1.6;
}

.instructions ol {
  margin: 10px 0;
  padding-left: 20px;
}

.instructions ol li {
  margin: 8px 0;
  line-height: 1.6;
}

.code-block {
  background: #2c3e50;
  color: #fff;
  padding: 15px;
  border-radius: 4px;
  margin: 10px 0;
}

.code-block pre {
  margin: 0;
}

.code-block code {
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.6;
}

code {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', Courier, monospace;
  color: #e74c3c;
  font-size: 13px;
}
</style>

